package com.uy.cuantoconocesdeuruguay.utiles;

import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.uy.cuantoconocesdeuruguay.MainActivity;
import com.uy.cuantoconocesdeuruguay.WakeLocker;
import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;

public class NotificationsUtils {
    private static final String SENDER_ID = "276058228905";
    private static final String DISPLAY_MESSAGE_ACTION = "com.uy.cuantoconocesdeuruguay.utiles.DISPLAY_MESSAGE";
    private static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private static GoogleCloudMessaging gcm;
    private static String regId;
	private static Activity activity;
    //private static AtomicInteger msgId = new AtomicInteger();
    
	public static void createUploadNotification(boolean success, Activity activity){
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis() + 100); //100 MILLISECONDS FROM NOW
		activity.getBaseContext();
		AlarmManager alarmManager = (AlarmManager) activity.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
		int id = (int) System.currentTimeMillis();
		Intent intent = new Intent(activity, NotificationReceiver.class);
		intent.putExtra(NotificationReceiver.SUCCESS, success);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(activity.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
	}

	private static String getRegistrationId(Context context) {
	    final SharedPreferences prefs = getGCMPreferences(context);
	    String registrationId = prefs.getString(PROPERTY_REG_ID, StringPool.BLANK);
	    if (registrationId.isEmpty()) {
	        return StringPool.BLANK;
	    }
	    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
	    int currentVersion = getAppVersion(context);
	    if (registeredVersion != currentVersion) {
	        return StringPool.BLANK;
	    }
	    return registrationId;
	}
	public static synchronized void registerGCM(Activity activity){
		checkPlayServices(activity);
		NotificationsUtils.activity = activity;
		gcm = GoogleCloudMessaging.getInstance(activity);
        regId = getRegistrationId(activity.getApplicationContext());
        if (!MainActivity.receiverRegistered){
        	MainActivity.receiverRegistered = true;
        	try{
        		activity.registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        	}catch(Exception e){
				GoogleAnalyticsTracker.trackException(activity, e);
        		e.printStackTrace();
        	}
        }
        if (regId.isEmpty()) {
            registerInBackground(activity);
        }else if (!regId.equals(MainActivity.userData.getRegId())){
        	try {
				ServerConnector.setGoogleGCMRegId(regId);
			} catch (ConnectivityException e) {
				GoogleAnalyticsTracker.trackException(activity, e);
				e.printStackTrace();
			}
        }
	}
	private static void registerInBackground(final Activity activity) {
	    new AsyncTask<Void,Void,String>() {
	        @Override
	        protected String doInBackground(Void... params) {
	            String msg = StringPool.BLANK;
	            try {
	                if (gcm == null) {
	                    gcm = GoogleCloudMessaging.getInstance(activity.getApplicationContext());
	                }
	                regId = gcm.register(SENDER_ID); 
	                msg = "Device registered, registration ID=" + regId;
	                
	                try {
						ServerConnector.setGoogleGCMRegId(regId);
					} catch (ConnectivityException e) {
						GoogleAnalyticsTracker.trackException(activity, e);
						e.printStackTrace();
					}
	                
	                storeRegistrationId(activity.getApplicationContext(), regId);
	            } catch (IOException e) {
					GoogleAnalyticsTracker.trackException(activity, e);
	                msg = "Error :" + e.getMessage();
	            }
	            return msg;
	        }

	        @Override
	        protected void onPostExecute(String msg) {
	        }
	    }.execute(null, null, null);
	}
	private static SharedPreferences getGCMPreferences(Context context) {
	    return context.getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
	}
	private static int getAppVersion(Context context) {
	    try {
	        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
	        return packageInfo.versionCode;
	    } catch (NameNotFoundException e) {
			GoogleAnalyticsTracker.trackException(activity, e);
	        throw new RuntimeException("Could not get package name: " + e);
	    }
	}
	private static boolean checkPlayServices(final Activity activity) {
	    final int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
	    if (resultCode != ConnectionResult.SUCCESS) {
	        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
//	        	activity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						GooglePlayServicesUtil.getErrorDialog(resultCode, activity, PLAY_SERVICES_RESOLUTION_REQUEST).show();
//					}
//				});
	        } else {
	            activity.finish();
	        }
	        return false;
	    }
	    return true;
	}
	private static void storeRegistrationId(Context context, String regId) {
	    final SharedPreferences prefs = getGCMPreferences(context);
	    int appVersion = getAppVersion(context);
	    SharedPreferences.Editor editor = prefs.edit();
	    editor.putString(PROPERTY_REG_ID, regId);
	    editor.putInt(PROPERTY_APP_VERSION, appVersion);
	    editor.commit();
	}
	private final static BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	//String newMessage = intent.getExtras().getString("Culo");
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(activity.getApplicationContext());        
            //Toast.makeText(activity, newMessage, Toast.LENGTH_LONG).show();             
            // Releasing wake lock
            WakeLocker.release();
        }
    };
}
